﻿using KnifeZ.PersonalNotePad.Views;
using KnifeZ.PersonalNotePad.Views.Habitica;
using KnifeZ.XamarinDomain;
using KnifeZ.XamarinDomain.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace KnifeZ.PersonalNotePad.ViewModels
{
    public class TodoItemViewModel : BaseViewModel
    {
        public ObservableCollection<TodoItem> Items { get; set; }
        public Command LoadItemsCommand { get; set; }
        public TodoItemViewModel()
        {
            Title = "Browse";
            Items = new ObservableCollection<TodoItem>();
            LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());

            MessagingCenter.Subscribe<NewItemPage>(this, "RefreshTodoList", async (obj) =>
            { 
               await  ExecuteLoadItemsCommand();
            });
        }


        async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;
            try
            {
                Items.Clear();
                var items = await DB.Table<TodoItem>().ToListAsync();
                foreach (var item in items)
                {
                    Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
    }
}
